package com.inno.gateway.error;

import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inno.gateway.entity.CommonReturnType;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GatewayErrorHandler implements ErrorWebExceptionHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public Mono<Void> handle(ServerWebExchange exchange,  Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        int code = 200;
        String message = "";
        if (ex instanceof SaTokenException){
            code = 401;
            message = "登录状态异常";
        }else {
            code = 500;
            message = "系统繁忙";
        }
        CommonReturnType<Object> fail = CommonReturnType.fail(code, message);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        return writeErrorInfo(response, fail);
    }

    private Mono<Void> writeErrorInfo(ServerHttpResponse response, CommonReturnType<Object> fail) {
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            byte[] bytes = null;
            try {
                bytes = objectMapper.writeValueAsBytes(fail);
                return bufferFactory.wrap(bytes);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
